package com.minedata.authorization.config;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.minedata.authorization.bean.UserBean;
import com.minedata.authorization.service.UserService;

public class StatelessAuthorizingRealm extends AuthorizingRealm {

	@Autowired
	private UserService userService;
	
	@Override
	public boolean supports(AuthenticationToken token) {
		return token instanceof StatelessAuthenticationToken;
	}

	/**
	 * 授权
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		System.out.println("StatelessRealm.doGetAuthorizationInfo()");
		// 根据用户名查找角色，请根据需求实现
		String username = (String) principals.getPrimaryPrincipal();
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();

		// 这里模拟admin账号才有role的权限.
		if ("admin".equals(username)) {
			authorizationInfo.addRole("admin");
		}
		return authorizationInfo;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		System.out.println("StatelessRealm.doGetAuthenticationInfo()");

		StatelessAuthenticationToken statelessToken = (StatelessAuthenticationToken) token;
		

		UserBean userBean = null;
		if(statelessToken.byId){
			Integer id = (Integer) statelessToken.getPrincipal();
			userBean = userService.findById(id);
		}else{
			String username = (String) statelessToken.getPrincipal();
			userBean = userService.findByUsername(username);
		}

		
		

		// 在服务器端生成客户端参数消息摘要
		String serverDigest = HmacSHA256Utils.digest(userBean.getUsername(), userBean.getPassword());

		System.out.println(serverDigest + "," + statelessToken.getCredentials());
		// 然后进行客户端消息摘要和服务器端消息摘要的匹配
		SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(userBean, serverDigest, getName());
		return authenticationInfo;
	}
}
